package shopping

import (
    "time"
	"strconv"
	"dhfshop/models/shopping"
	"dhfshop/controllers/base"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type FavoritesController struct {
	base.BaseController
}

// 获取最新的收藏内容
func (this *FavoritesController) GetFavorites() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	query["buyer_id"] = strconv.FormatInt(curUserId, 10)
	l, cnt, err := shopping.GetAllFavorites(query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount  int64                 `json:"total_count"`
		Favorites  []*shopping.Favorites  `json:"favorites"`
	}{TotalCount: cnt, Favorites: l}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *FavoritesController) Post() {
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	if curUserId == 0 {
	    this.ServeError("user is not login")
	    return
	}
	var v shopping.Favorites
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.ItemIdStr, "item_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	v.BuyerId = int64(curUserId)
	var err error
	v.ItemId, err = strconv.ParseInt(v.ItemIdStr, 10, 64)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	favId, err := shopping.AddFavorites(&v)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	v.FavId = favId
	rsp := struct {
		FavId     int64        `json:"fav_id"`
	    Created   time.Time  `json:"created"`
	}{FavId: v.FavId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *FavoritesController) Delete() {
	favId, err := this.GetInt("fav_id")
	if err != nil {
	    this.ServeError(err.Error())
	    return
	}
	if err := shopping.RemoveFavoritesItem(favId); err != nil {
	    this.ServeError(err.Error())
	    return
	}
    r := struct {
		    FavId       int       `json:"fav_id"`
	        Modified  time.Time   `json:"modified"`
	    }{FavId:favId, Modified:time.Now().UTC()}
	this.Data["json"] = r 
	this.ServeJSON()
}
